package com.yiwenup.leetcode.site;

import java.util.Stack;

/**
 * https://leetcode-cn.com/problems/valid-parentheses/
 */
public class No020 {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        int n = s.length();
        for (int i = 0; i < n; i++) {
            char c = s.charAt(i);
            if (c == '{' || c == '[' || c == '(') {
                stack.push(c);
            } else {
                if (stack.isEmpty()) return false;

                char top = stack.pop();
                if (top != '(' && c == ')') return false;
                if (top != '{' && c == '}') return false;
                if (top != '[' && c == ']') return false;
            }
        }

        return stack.isEmpty();
    }
}
